package com.example.ice.fittime.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.example.ice.fittime.R;
import com.example.ice.fittime.adapter.user.ArticleAdapter;
import com.example.ice.fittime.adapter.user.PhotoAdapter;
import com.example.ice.fittime.entry.user.ActivityUserBean;
import com.example.ice.fittime.entry.user.ArticleBean;
import com.example.ice.fittime.entry.user.StatisticsBean;
import com.example.ice.fittime.entry.user.UserBean;
import com.example.ice.fittime.util.NetUtil;

import java.util.Date;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

public class UserActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener, SwipeRefreshLayout.OnRefreshListener, View.OnClickListener {

    private RecyclerView photo_rv;
    private RecyclerView articles_rv;
    private int offset = 0;
    private int limit = 20;
    private long timestamp;
    private int user_id;
    private PhotoAdapter photoAdapter;
    private ArticleAdapter articleAdapter;
    private ImageView avatar_url;
    private TextView location;
    private TextView description;
    private TextView name;
    private ImageView back;
    private FrameLayout more;
    private TextView has_follower;
    private TextView has_followee;
    private TextView has_praise_from_other;
    private SwipeRefreshLayout srl;
    private ImageView iv_all;
    private View popup;
    //    private CoordinatorLayout contentView;
    private PopupWindow popupWindow;
    private TextView popup_share;
    private TextView popup_cancel;
    private TextView popup_blacklist;
//    private ImageView user_icon;
//    private Bitmap user_icon_bitmap;
//    private int widthPixels;
//    private int heightPixels;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user);

        hideStatusBar();
        getInfo();
        initView();
        initData();
    }

    private void hideStatusBar() {
        View decorView = getWindow().getDecorView();
        int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
        decorView.setSystemUiVisibility(uiOptions);
    }

    /**
     * 获取开启这个activity时传递的数据
     */
    private void getInfo() {
        Intent intent = getIntent();
        user_id = intent.getIntExtra("user_id", 15627);
        timestamp = new Date().getTime();
    }

    private void initData() {
        getUserBean();
        getStatisticsBean();
        getArticleBean();
        getActivityUserBean(timestamp, 20, 0);
    }

    private void getUserBean() {
        NetUtil.getUserBean(user_id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<UserBean>() {
                    @Override
                    public void call(UserBean userBean) {
                        location.setText(userBean.getLocation());
                        description.setText(userBean.getDescription());
                        name.setText(userBean.getName());
                        Glide.with(UserActivity.this)
                                .load(userBean.getAvatar_url())
                                .asBitmap()
                                .centerCrop()
                                .into(new BitmapImageViewTarget(avatar_url) {
                                    @Override
                                    protected void setResource(Bitmap resource) {
//                                        user_icon_bitmap = resource;
//                                        user_icon.setImageBitmap(user_icon_bitmap);
//                                        user_icon.setOnClickListener(UserActivity.this);
                                        RoundedBitmapDrawable circularBitmapDrawable =
                                                RoundedBitmapDrawableFactory.create(getResources(), resource);
                                        circularBitmapDrawable.setCircular(true);
                                        avatar_url.setImageDrawable(circularBitmapDrawable);
                                    }
                                });
                    }
                });
    }

    private void getActivityUserBean(long timestamp, int limit, int offset) {
        this.offset += limit;
        NetUtil.getActivityUserObservable(user_id, timestamp, limit, offset)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<List<ActivityUserBean>>() {
                    @Override
                    public void call(List<ActivityUserBean> activityUserBeen) {
                        photoAdapter.addAll(activityUserBeen);
                        srl.setRefreshing(false);
                    }
                });
    }

    private void getArticleBean() {
        NetUtil.getArticleBean(user_id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<List<ArticleBean>>() {
                    @Override
                    public void call(List<ArticleBean> articleBean) {
                        articleAdapter.addAll(articleBean);
                        srl.setRefreshing(false);
                    }
                });
    }

    private void getStatisticsBean() {
        NetUtil.getStatisticsBeanObservable(user_id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<StatisticsBean>() {
                    @Override
                    public void call(StatisticsBean statisticsBean) {
                        has_follower.setText(String.valueOf(statisticsBean.getHas_follower()));
                        has_followee.setText(String.valueOf(statisticsBean.getHas_followee()));
                        has_praise_from_other.setText(String.valueOf(statisticsBean.getHas_praise_from_other()));
                    }
                });
    }

    private void initView() {
//        widthPixels = getResources().getDisplayMetrics().widthPixels;
//        heightPixels = getResources().getDisplayMetrics().heightPixels;
//        user_icon = (ImageView) findViewById(user_icon);
//        contentView = (CoordinatorLayout) findViewById(R.id.contentView);
        iv_all = (ImageView) findViewById(R.id.iv_all);
        initRadioGroup();
        initRecyclerView();
        initSwipeRefresh();
        initHeadView();
        initPopupWindow();
    }

    private void initPopupWindow() {
        popup = LayoutInflater.from(this).inflate(R.layout.popup, null);
        popup_share = (TextView) popup.findViewById(R.id.popup_share);
        popup_cancel = (TextView) popup.findViewById(R.id.popup_cancel);
        popup_blacklist = (TextView) popup.findViewById(R.id.popup_blacklist);
        popup_share.setOnClickListener(this);
        popup_cancel.setOnClickListener(this);
        popup_blacklist.setOnClickListener(this);
        popupWindow = new PopupWindow(popup, ViewGroup.LayoutParams.MATCH_PARENT, 300);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                iv_all.setVisibility(View.GONE);
            }
        });
        popupWindow.setAnimationStyle(R.style.AnimBottom);
        popupWindow.setFocusable(true);//不这样设置的话别的按钮会强调焦点
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.more:
                boolean showing = popupWindow.isShowing();
                if (!showing) {
                    popupWindow.showAtLocation(more, Gravity.BOTTOM, 0, 0);
                    iv_all.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.popup_blacklist:
                Toast.makeText(this, "black", Toast.LENGTH_SHORT).show();
                popupWindow.dismiss();
                break;
            case R.id.popup_cancel:
                Toast.makeText(this, "cancel", Toast.LENGTH_SHORT).show();
                popupWindow.dismiss();
                break;
            case R.id.popup_share:
                Toast.makeText(this, "share", Toast.LENGTH_SHORT).show();
                popupWindow.dismiss();
                break;
//            case user_icon:
//                showUserIcon();
//                break;
        }
    }

    private void initHeadView() {
        initActionBar();
        avatar_url = (ImageView) findViewById(R.id.avatar_url);
        location = (TextView) findViewById(R.id.location);
        description = (TextView) findViewById(R.id.description);
        has_follower = (TextView) findViewById(R.id.has_follower);
        has_followee = (TextView) findViewById(R.id.has_followee);
        has_praise_from_other = (TextView) findViewById(R.id.has_praise_from_other);
    }

    private void initActionBar() {
        name = (TextView) findViewById(R.id.name);
        back = (ImageView) findViewById(R.id.back);
        more = (FrameLayout) findViewById(R.id.more);
        back.setOnClickListener(this);
        more.setOnClickListener(this);
    }

    private void initSwipeRefresh() {
        srl = (SwipeRefreshLayout) findViewById(R.id.srl);
        srl.setOnRefreshListener(this);
        srl.setColorSchemeColors(Color.BLUE);
        srl.setRefreshing(true);
    }

    private void initRecyclerView() {
        photo_rv = (RecyclerView) findViewById(R.id.photo_rv);
        articles_rv = (RecyclerView) findViewById(R.id.articles_rv);
        photo_rv.setVisibility(View.VISIBLE);
        photoAdapter = new PhotoAdapter(this);
        articleAdapter = new ArticleAdapter(this);
        photo_rv.setAdapter(photoAdapter);
        articles_rv.setAdapter(articleAdapter);
        photo_rv.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    if (recyclerView.getChildAdapterPosition(recyclerView.getChildAt(recyclerView.getChildCount() - 1))
                            == photoAdapter.getItemCount() - 1) {
                        loadMore(20, offset);
                    }
                }
            }
        });
    }

    private void loadMore(int limit, int offset) {
        timestamp = new Date().getTime();
        getActivityUserBean(timestamp, limit, offset);
    }

    private void initRadioGroup() {
        RadioGroup rg = (RadioGroup) findViewById(R.id.user_rg);
        rg.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.user_rb_articles:
                photo_rv.setVisibility(View.GONE);
                articles_rv.setVisibility(View.VISIBLE);
                break;
            case R.id.user_rb_photo:
                articles_rv.setVisibility(View.GONE);
                photo_rv.setVisibility(View.VISIBLE);
                break;
        }
    }

    @Override
    public void onRefresh() {
//        getActivityUserBean(timestamp,20,offset); 有问题
        if (photoAdapter.getItemCount() == 0) {
            timestamp = new Date().getTime();
            getActivityUserBean(timestamp, 20, 0);
        } else if (articleAdapter.getItemCount() == 0) {
            getArticleBean();
        } else {
            // TODO: 2016/10/14
            srl.setRefreshing(false);
        }
    }

//    public void showUserIcon() {
//        int bitmapW = user_icon.getWidth();
//        int bitmapH = user_icon.getHeight();
//        float scaleW = widthPixels * 1.0f / bitmapW;
//        float scaleH = heightPixels * 1.0f / bitmapH;
////        user_icon.setAlpha(0);
//        ViewCompat.animate(user_icon)
//                .alpha(0)
//                .translationX((widthPixels - bitmapW) / 2)
//                .translationY((heightPixels - bitmapH) / 2)
//                .scaleX(scaleW)
//                .scaleY(scaleH)
//                .setDuration(1000)
//                .start();
//    }

}
